package com.vaye.im.intercepter;


import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSONObject;
import com.vaye.common.utils.AccessTimeHolder;
import com.vaye.common.utils.MDCUtils;
import com.vaye.common.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 **/
@Component
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        if (requestURI.startsWith("/jgroups")) {
            return true;
        }
        String token = httpServletRequest.getHeader("token");
        Object loginIdByToken = StpUtil.getLoginIdByToken(token);
        if (ObjectUtils.isEmpty(loginIdByToken)) {
            log.error("用户身份认证失败");
            throw new IllegalArgumentException("用户身份认证失败");
        }
        MDCUtils.putTraceId(httpServletRequest);
        UserContextHolder.setUserName(((JSONObject) StpUtil.getSessionByLoginId(Long.valueOf(loginIdByToken + "")).getDataMap().get(SaSession.USER)).getString("account"));
        AccessTimeHolder.start();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //清除用户信息
//        UserContextHolder.clearCurrentUser();
//        UserContextHolder.clearCurrentUser();
//        MDCUtils.clearTraceId();
//        long costTime = AccessTimeHolder.end();
//        log.info("reqUrl={},costTime={}毫秒",httpServletRequest.getRequestURI(),costTime);
    }
}
